home *** CD-ROM | disk | FTP | other *** search
/ Java Developer's Companion / Java Developer's Companion.iso / documentation / tutorial / intl / stepbystep / example-1.1 / WordMatch_orig.java next >
Encoding:
Java Source  |  1997-07-13  |  10.7 KB  |  394 lines

  1. import java.awt.*;
  2. import java.applet.*;
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import java.util.*;
  6.  
  7. public class WordMatch extends Applet 
  8.         implements ActionListener, ItemListener {
  9.  
  10.     // Number of displayed cards and words.
  11.     int numCards = 4;
  12.  
  13.     // Currently selected language.
  14.     int curLanguage;
  15.  
  16.     // card[i] refers to the i'th word.
  17.     int cards[];
  18.  
  19.     // words[i] refers to the i'th card.
  20.     int words[];
  21.  
  22.     // Currently selected card.
  23.     int curCard;
  24.  
  25.     // The components.
  26.     Box soundBox;
  27.     List languageList = new List();
  28.     Label statusBar = new Label("Ready");
  29.     Button scoreButton;
  30.     Box[] cardBoxes;
  31.     Box[] wordBoxes;
  32.  
  33.     // If true, the user has successfully matched all the words.
  34.     boolean done;
  35.     
  36.     // links[i] == j -> cards[i] is linked to words[j].
  37.     int links[];
  38.  
  39.     // Images of pictures.  There is one image for each different word.
  40.     Image images[];
  41.  
  42.     // The dimensions of the images.  They must all be the same size.
  43.     int imageW, imageH;
  44.  
  45.     int numWords;
  46.     String[] languages;
  47.     String[][] dictionary;
  48.  
  49.     // Width of language list.
  50.     int languageListW = 120;
  51.  
  52.     // Used to layout the components.
  53.     int gap = 10;
  54.  
  55.     /**
  56.      * Initialize the applet. Resize and load images.
  57.      */
  58.     public void init() {
  59.         imageW = Integer.parseInt(getParameter("image-w"));
  60.         imageH = Integer.parseInt(getParameter("image-h"));
  61.  
  62.         // Count number of languages
  63.         for (int i=1; ; i++) {
  64.             if (getParameter("language"+i) == null) {
  65.                 languages = new String[i-1];
  66.                 dictionary = new String[i-1][];
  67.                 break;
  68.             }
  69.         }
  70.  
  71.         // Count total number of words, based on the first language.
  72.         for (int i=0; i<languages.length; i++) {
  73.         StringTokenizer st = new StringTokenizer(
  74.                 getParameter("language"+(i+1)), "|");
  75.  
  76.             dictionary[i] = new String[st.countTokens()-1];
  77.             languages[i] = st.nextToken();
  78.             languageList.addItem(languages[i]);
  79.             
  80.         for (int j=0; j<dictionary[i].length; j++) {
  81.                 dictionary[i][j] = st.nextToken();
  82.         }
  83.         }
  84.         numWords = dictionary[0].length;
  85.  
  86.         // Create data structures.
  87.         cards = new int[numCards];
  88.         cardBoxes = new Box[numCards];
  89.         words = new int[numCards];
  90.         wordBoxes = new Box[numCards];
  91.         links = new int[numCards];
  92.         images = new Image[numWords];
  93.         curLanguage = 0;
  94.  
  95.         // Load the images.
  96.         for (int i=0; i<numWords; i++) {
  97.         images[i] = getImage(getCodeBase(), "rsrc/"
  98.         + dictionary[0][i] + ".gif");
  99.         }
  100.  
  101.         // Layout the components.  Use absoluting positioning.
  102.         setLayout(null);
  103.  
  104.         // Setup the score button.
  105.         scoreButton = new Button("Score");
  106.         add(scoreButton);
  107.         Dimension d = scoreButton.getPreferredSize();
  108.         scoreButton.setBounds(0, getSize().height-d.height, 
  109.             languageListW, d.height);
  110.         scoreButton.addActionListener(this);
  111.  
  112.         // Setup the language list.
  113.         add(languageList);
  114.         languageList.setBounds(0, 0, 
  115.             languageListW, getSize().height-d.height);
  116.         languageList.addItemListener(this);
  117.         languageList.select(curLanguage);
  118.  
  119.     // Setup the status bar.
  120.         add(statusBar);
  121.         statusBar.setBounds(languageListW+2*gap, getSize().height-d.height, 
  122.             getSize().width-languageListW-2*gap, d.height);
  123.  
  124.         // Setup sound box.
  125.         soundBox = new Box(getImage(getCodeBase(), "rsrc/sound.gif"));
  126.         add(soundBox);
  127.         soundBox.addItemListener(this);
  128.         soundBox.setBounds(0, 0, 32, 32);
  129.  
  130.     Font f = new Font("SansSerif", Font.PLAIN, 16);
  131.         for (int i=0; i<numCards; i++) {
  132.             // Setup the picture cards.
  133.             cardBoxes[i] = new Box(images[cards[i]]);
  134.             add(cardBoxes[i]);
  135.             cardBoxes[i].setBounds(languageListW+2*gap, 
  136.                 i*(imageH+gap), imageW, imageH);
  137.             cardBoxes[i].addItemListener(this);
  138.             cardBoxes[i].select(i == 0);
  139.  
  140.             // Setup up the word boxes.
  141.             wordBoxes[i] = new Box(dictionary[curLanguage][words[i]], f);
  142.             add(wordBoxes[i]);
  143.             wordBoxes[i].setBounds(languageListW+4*gap+2*imageW, 
  144.                 i*(imageH+gap), getSize().width, imageH);
  145.             wordBoxes[i].addItemListener(this);
  146.         }
  147.  
  148.         moveSoundBox();
  149.         newRound();
  150.     }
  151.  
  152.     /**
  153.      * Paint the screen.
  154.      */
  155.     public void paint(Graphics g) {
  156.         int x, y;
  157.  
  158.         // Paint links.
  159.         g.setColor(Color.black);
  160.         for (int i=0; i<numCards; i++) {
  161.             if (links[i] >= 0) {
  162.                 Point pt1 = cardBoxes[i].getLocation();
  163.                 Point pt2 = wordBoxes[links[i]].getLocation();
  164.  
  165.                 pt1.translate(imageW+gap, imageH/2);
  166.                 pt2.translate(-gap, imageH/2);
  167.  
  168.                 g.drawLine(pt1.x, pt1.y, pt2.x, pt2.y);
  169.             }
  170.     }
  171.     }
  172.  
  173.     public void itemStateChanged(ItemEvent evt) {
  174.         if (!done) {
  175.             statusBar.setText(null);
  176.         }
  177.         if (evt.getSource() == soundBox) {
  178.         "rsrc/" + dictionary[0][cards[curCard]] 
  179.         + "." + languages[curLanguage] + ".au");
  180.         play(getCodeBase(), "rsrc/" + dictionary[0][cards[curCard]] 
  181.         + "." + languages[curLanguage] + ".au");
  182.         }
  183.  
  184.         // Was the event fired from one of the picture cards?
  185.         for (int i=0; i<cardBoxes.length; i++) {
  186.             if (cardBoxes[i] == evt.getSource()) {
  187.             // In card box.
  188.                 cardBoxes[curCard].select(false);
  189.                 cardBoxes[i].select(true);
  190.                 curCard = i;
  191.  
  192.                 moveSoundBox();
  193.         repaint();
  194.                 break;
  195.         }
  196.         } 
  197.  
  198.         // Was the event fired from one of the words?
  199.         for (int i=0; i<wordBoxes.length; i++) {
  200.             if (wordBoxes[i] == evt.getSource()) {
  201.         // Break an old link if necessary.
  202.         for (int j=0; j<numCards; j++) {
  203.             if (links[j] == i) {
  204.             links[j] = -1;
  205.             }
  206.         }
  207.         links[curCard] = i;
  208.         repaint();
  209.             }
  210.         } 
  211.  
  212.         // Was the event fired from the language list?
  213.         if (evt.getSource() == languageList) {
  214.             curLanguage = languageList.getSelectedIndex();
  215.             for (int i=0; i<wordBoxes.length; i++) {
  216.                 wordBoxes[i].setText(dictionary[curLanguage][words[i]]);
  217.             }
  218.         }
  219.     }
  220.  
  221.     void moveSoundBox() {
  222.     // Move the sound box.
  223.     Point pt = cardBoxes[curCard].getLocation();
  224.     soundBox.setLocation(
  225.         pt.x+imageW-soundBox.getSize().width/2, 
  226.         pt.y+imageH-soundBox.getSize().height/2);
  227.     }
  228.  
  229.     public void actionPerformed(ActionEvent evt) {
  230.         if (evt.getSource() == scoreButton) {
  231.             if (done) {
  232.             scoreButton.setLabel("Score");
  233.                 newRound();
  234.                 repaint();
  235.             }
  236.             int count = 0;
  237.             for (int i=0; i<numCards; i++) {
  238.                 if (links[i] == -1) {
  239.                     statusBar.setText("You have not yet matched all the words.");
  240.                     return;
  241.                 }
  242.                 if (cards[i] == words[links[i]]) {
  243.                     count++;
  244.                 }
  245.             }
  246.             if (count == numCards) {            
  247.         statusBar.setText("Congratulations, they're all right!");
  248.                 done = true;
  249.                 scoreButton.setLabel("New Game");
  250.             } else if (count == 1) {
  251.         statusBar.setText("There is only 1 correct match.");
  252.             } else if (count == 0) {
  253.         statusBar.setText("There are no correct matches.");
  254.             } else {
  255.         statusBar.setText("There are " + count + " correct matches.");
  256.             }
  257.         }
  258.     }
  259.  
  260.     /**
  261.      * Starts a new round.
  262.      */
  263.     public void newRound() {
  264.         boolean[] picked = new boolean[numWords];
  265.  
  266.         statusBar.setText(null);
  267.         done = false;
  268.  
  269.         // Pick new cards.
  270.         for (int i=0; i<numCards; i++) {
  271.         while (true) {
  272.                 int r = (int)Math.floor(Math.random() * numWords);
  273.  
  274.                 if (!picked[r]) {
  275.                 cards[i] = r;
  276.                 words[i] = r;
  277.                 links[i] = -1;
  278.                 picked[r] = true;
  279.                     break;
  280.                 }
  281.             }
  282.     }
  283.  
  284.         // Scramble the pictures
  285.         for (int i=0; i<100; i++) {
  286.         int r = (int)Math.floor(Math.random() * numCards);
  287.             int t = cards[r];
  288.  
  289.             cards[r] = cards[i%numCards];
  290.             cards[i%numCards] = t;
  291.         }
  292.  
  293.  
  294.     // Initialize the new pictures and words.
  295.     for (int i=0; i<numCards; i++) {
  296.         cardBoxes[i].setImage(images[cards[i]]);
  297.         wordBoxes[i].setText(dictionary[curLanguage][words[i]]);
  298.     }
  299.     }
  300.  
  301.  
  302.     // Added by K.A. Smith 10/25/95 
  303.     public String getAppletInfo() {
  304.        return "Author: Patrick Chan\nVersion: 2.0, June 1 1997";
  305.     }
  306. }
  307.  
  308. class Box extends Canvas implements ItemSelectable {
  309.     Font font;
  310.     Image image;
  311.     String string;
  312.     boolean selected;
  313.  
  314.     Box(Image image) {
  315.         this.image = image;
  316.         addMouseListener(new MouseEventHandler());
  317.     }
  318.  
  319.     Box(String string, Font f) {
  320.         this.string = string;
  321.         font = f;
  322.         addMouseListener(new MouseEventHandler());
  323.     }
  324.  
  325.     public void select(boolean s) {
  326.         selected = s;
  327.         repaint();
  328.     }
  329.  
  330.     public void setText(String s) {
  331.         string = s;
  332.         repaint();
  333.     }
  334.  
  335.     public void setImage(Image i) {
  336.         image = i;
  337.         repaint();
  338.     }
  339.  
  340.     public Object[] getSelectedObjects() {
  341.     Object[] result;
  342.         if (selected) {
  343.             result = new Object[1];
  344.             result[0] = this;
  345.         } else {
  346.             result = new Object[0];
  347.         }
  348.         return result;
  349.     }
  350.  
  351.     public void paint(Graphics g) {
  352.         int w = getSize().width;
  353.         int h = getSize().height;
  354.  
  355.         // If it's an image, paint it.
  356.         if (image != null) {
  357.             g.drawImage(image, 0, 0, this);
  358.  
  359.             if (selected) {
  360.                 g.setColor(Color.red);
  361.                 g.drawRect(0, 0, w-1, h-1);
  362.             }
  363.         }
  364.         // If it's a string, paint it.
  365.         if (string != null) {
  366.             g.setFont(font);
  367.             FontMetrics fontM = g.getFontMetrics();
  368.  
  369.         g.setColor(Color.black);
  370.         g.drawString(string, 0, (h-fontM.getHeight())/2+fontM.getAscent());
  371.         }
  372.     }
  373.  
  374.     class MouseEventHandler extends MouseAdapter {
  375.         public void mousePressed(MouseEvent evt) {
  376.         ItemEvent e = new ItemEvent(Box.this, 
  377.             ItemEvent.ITEM_STATE_CHANGED, string, ItemEvent.SELECTED);
  378.     
  379.         if (ItemListener != null) {
  380.             ItemListener.itemStateChanged(e);
  381.         }
  382.         }
  383.     }
  384.  
  385.     ItemListener ItemListener;
  386.     public synchronized void addItemListener(ItemListener l) {
  387.     ItemListener = AWTEventMulticaster.add(ItemListener, l);
  388.     }
  389.  
  390.     public synchronized void removeItemListener(ItemListener l) {
  391.     ItemListener = AWTEventMulticaster.remove(ItemListener, l);
  392.     }
  393. }
  394.